package com.sd.activity;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alex.books.BaseBook;
import com.alex.database.BookDao;
import com.sd.activity.r.R;
import com.sd.util.BookCabin;
import com.sd.util.LoadingProgressDialog;
import com.sd.view.FilesAdapter;
import com.sd.view.ToastManager;

/**
 * 
 * 书籍选择界面
 * 
 * @author Alex.Lu
 * 
 */
public class FilesActivity extends BaseActivity implements OnItemClickListener,
		OnClickListener {

	private TextView mParentPath;
	/**
	 * 返回按钮
	 */
	private ImageButton mReturn;
	/**
	 * 搜索按钮
	 */
	private ImageButton mSearch;
	/**
	 * 文件列表
	 */
	private ListView mFileList;
	/**
	 * 文件数据
	 */
	private List<Map<String, Object>> mData;

	private String mStorage = Environment.getExternalStorageDirectory()
			.getAbsolutePath();
	private String mDir = Environment.getExternalStorageDirectory()
			.getAbsolutePath();
	private String mParentDir = "";

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			mParentPath.setText(mDir);
			LoadingProgressDialog.dismiss();
			FilesAdapter adapter = new FilesAdapter(FilesActivity.this, mData);
			mFileList.setAdapter(adapter);
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_files);

		mFileList = (ListView) findViewById(R.id.files_list);
		mFileList.setOnItemClickListener(this);

		mReturn = (ImageButton) findViewById(R.id.return_btn);
		mReturn.setOnClickListener(this);

		mSearch = (ImageButton) findViewById(R.id.search_files);
		mSearch.setOnClickListener(this);

		mParentPath = (TextView) findViewById(R.id.parent_path);
		new Thread(new mThread()).start();
	}

	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;

		File f = new File(mDir);
		File[] files = f.listFiles();

		mParentDir = "";
		if (!mDir.equals(mStorage)) {
			mParentDir = f.getParent();
			map = new HashMap<String, Object>();
			map.put("title", "Back to ../");
			map.put("info", mParentDir);
			map.put("img", R.drawable.files_back_btn);
			list.add(map);
		}
		if (files != null) {
			for (int i = 0; i < files.length; i++) {

				map = new HashMap<String, Object>();
				map.put("title", files[i].getName());
				map.put("info", files[i].getPath());
				if (files[i].isDirectory()) {
					map.put("img", R.drawable.ex_folder);
					list.add(map);
				} else {
					map.put("img", R.drawable.ex_doc);
					if (files[i].getName().endsWith(".txt")
							|| files[i].getName().endsWith(".umd")
							|| files[i].getName().endsWith(".epub")) {
						list.add(map);
					}
				}
			}
		}
		Collections.sort(list, ca);
		return list;
	}

	private Comparator<Map<String, Object>> ca = new Comparator<Map<String, Object>>() {

		@Override
		public int compare(Map<String, Object> object1,
				Map<String, Object> object2) {
			// TODO Auto-generated method stub
			String s1 = (String) object1.get("title");
			String s2 = (String) object2.get("title");
			int len1 = s1.length();
			int len2 = s2.length();
			int n = Math.min(len1, len2);
			char v1[] = s1.toCharArray();
			char v2[] = s2.toCharArray();
			int pos = 0;

			while (n-- != 0) {
				char c1 = v1[pos];
				char c2 = v2[pos];
				if (c1 != c2) {
					return c1 - c2;
				}
				pos++;
			}
			return len1 - len2;
		}
	};

	List<Map<String, Object>> list0 = new ArrayList<Map<String, Object>>();
	Map<String, Object> map0 = null;

	private List<Map<String, Object>> getFileList(File file) {

		// 列出指定路径下所有文件
		File[] files = file.listFiles();

		if(files == null){
			return list0;
		}
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isFile()) {
				// 如果是文件，则检查其扩展名是否为想要的图片类型
				if (getImageFile(f.getPath())) {
					// 是，则添加进全局量
					map0 = new HashMap<String, Object>();
					map0.put("title", files[i].getName());
					map0.put("info", files[i].getPath());
					if (files[i].isDirectory())
						map0.put("img", R.drawable.ex_folder);
					else
						map0.put("img", R.drawable.ex_doc);
					list0.add(map0);
					// mFiles.add(f);
				}
			} else if (f.isDirectory()) {

				// 不是文件，而是文件夹，进一步检查这个文件夹下面文件
				getFileList(f);
			}
		}
		Collections.sort(list0, ca);
		return list0;
	}

	private void atuo() {
		list0.clear();
		map0 = new HashMap<String, Object>();
		map0.put("title", "Back to ../");
		map0.put("info", mStorage);
		map0.put("img", R.drawable.ex_folder);
		list0.add(map0);

		File f = new File(mStorage);
		getFileList(f);
		mData = list0;
		FilesAdapter adapter = new FilesAdapter(this, mData);
		mFileList.setAdapter(adapter);
	}

	private boolean getImageFile(String path) {
		if (path.endsWith(".txt") || path.endsWith(".umd")
				|| path.endsWith(".epub")) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		Log.d("MyListView4-click", (String) mData.get(position).get("info"));
		if ((Integer) mData.get(position).get("img") == R.drawable.ex_folder
				|| (Integer) mData.get(position).get("img") == R.drawable.files_back_btn) {
			mDir = (String) mData.get(position).get("info");
			new Thread(new mThread()).start();
		} else {
			CheckBox box = (CheckBox) view.findViewById(R.id.checkBox);
			if (box.isChecked()) {
				mDir = (String) mData.get(position).get("info");
				BookCabin.getInstance().removeBook(this, mDir);
				ToastManager.getInstance().showText(this,
						R.string.msg_success_delete);
			} else {
				BaseBook book = new BaseBook();
				book.mBookName = (String) mData.get(position).get("title");
				book.mBookPath = (String) mData.get(position).get("info");
				book.mBookId = (int) BookDao.getInstance().insertBook(this,
						book);
				BookCabin.getInstance().addBook(book);
				ToastManager.getInstance().showText(this,
						R.string.msg_success_add);
			}
			box.setChecked(!box.isChecked());
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (mParentDir != null && !mParentDir.equals("")) {
			mDir = (String) mData.get(0).get("info");
			new Thread(new mThread()).start();
		} else {
			finish();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.return_btn:
			finish();
			break;
		case R.id.search_files:
			atuo();
			break;
		default:
			break;
		}
	}

	private class mThread implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			BookCabin.getInstance().refresh(FilesActivity.this, "");
			mData = getData();
			mHandler.sendEmptyMessage(0);
		}
	}

};
